package com.ziyun.erp.modules.member.service.impl;

import com.ziyun.erp.modules.member.entity.UserShareEntity;
import com.ziyun.erp.modules.member.service.UserShareService;
import io.renren.common.exception.RRException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.Query;

import com.ziyun.erp.modules.member.dao.UserOrderCommissionDao;
import com.ziyun.erp.modules.member.entity.UserOrderCommissionEntity;
import com.ziyun.erp.modules.member.service.UserOrderCommissionService;
import org.springframework.transaction.annotation.Transactional;


@Service("userOrderCommissionService")
public class UserOrderCommissionServiceImpl extends ServiceImpl<UserOrderCommissionDao, UserOrderCommissionEntity> implements UserOrderCommissionService {

    @Autowired
    private UserShareService userShareService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        Page<UserOrderCommissionEntity> page = this.selectPage(
                new Query<UserOrderCommissionEntity>(params).getPage(),
                new EntityWrapper<UserOrderCommissionEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 查询 冻结时间超过 7 天 的订单
     * @param page
     * @return
     */
    @Override
    public Page<UserOrderCommissionEntity> selectFreezeCommissionPage(Page<UserOrderCommissionEntity> page) {
        List<UserOrderCommissionEntity> list = baseMapper.selectFreezeCommission();
        return page.setRecords(list);
    }

    /**
     * 佣金解冻
     * @param userOrderCommissionEntityList
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void commissionThawing(List<UserOrderCommissionEntity> userOrderCommissionEntityList) {
        for(UserOrderCommissionEntity userOrderCommissionEntity:userOrderCommissionEntityList){
            if(userOrderCommissionEntity.getStatus() ==  2){
                continue;
            }

            // 订单佣金记录
            Map<String,Object> updateMap = new HashMap<>();
            updateMap.put("status",2);
            baseMapper.updateByMap(updateMap,userOrderCommissionEntity.getOrderId());

            // 用户佣金钱包
            UserShareEntity userShareEntity = userShareService.selectById(userOrderCommissionEntity.getSUserId());
            boolean bool = userShareService.updateCommissionThawing(userShareEntity.getUserId(),
                    userOrderCommissionEntity.getCommission(),userShareEntity.getUsableCommission());

            if(!bool){
                String msg = "订单号："+userOrderCommissionEntity.getOrderId()+" 佣金解冻失败！";
                throw new RRException(msg);
            }

        }
    }

}
